//
//  HomeViewController.swift
//  HoneyBee
//
//  Created by point on 2018/1/24.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import MJRefresh

private let kCellID = "kCellID"

class HomeViewController: BaseViewController {
    fileprivate lazy var bag: DisposeBag = DisposeBag()
    @IBOutlet weak var tableView: UITableView!
    fileprivate lazy var schoolViewModel: SchoolViewModel = SchoolViewModel()
    lazy var homeSearchView:HomeSearchView =  HomeSearchView()
    lazy var locService = BMKLocationManager()
    var currentLocation:CLLocation = CLLocation()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        mapBtnClick()
        schoolViewModel.loadData(type: .mpLoadDataUp)
    }
}

// MARK: - 搜索
extension HomeViewController:UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        let vm = SearchOraganizaionViewModel.init()
        vm.modelObserable = Array.init(schoolViewModel.modelObserable)
        vm.location = self.currentLocation
        let  searchVC = SerchOraganizaitonViewController.init(vm: vm)
        navigationController?.pushViewController(searchVC, animated: true)
        return false
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        schoolViewModel.keyWord = textField.text!
        self.schoolViewModel.publishSubData.onNext(.mpLoadDataUp)
    }
    
    @objc func networkError() {
        self.hideEmptyView()
        self.schoolViewModel.publishSubData.onNext(.mpLoadDataUp)
    }
}

// MARK:- 页面logic
extension HomeViewController {
    func mapBtnClick() {
        self.homeSearchView.mapBtn.rx.tap.subscribe { [weak self](event:Event<()>) in
            let vc = SchoolMapViewController()
            vc.modelArr = (self?.schoolViewModel.modelObserable)!
            self?.navigationController?.pushViewController(vc, animated: true)
            }.disposed(by: bag)
    }
}

// MARK:- table代理
extension HomeViewController:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return schoolViewModel.modelObserable.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kCellID, for: indexPath) as! HomeTableViewCell
        cell.configModel(model: schoolViewModel.modelObserable[indexPath.item], index: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 96
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let vc = SchoolDetailViewController()
        let model = schoolViewModel.modelObserable[indexPath.item]
        vc.schoolID = "\(model.id)"
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK:- 设置UI
extension HomeViewController {
    fileprivate func setupUI(){
        
        view.backgroundColor = kColorC2
        tableView.register(UINib(nibName: "HomeTableViewCell", bundle: nil), forCellReuseIdentifier: kCellID)
        tableView.separatorStyle = .none
        
        schoolViewModel.vc = self
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.schoolViewModel.publishSubData.onNext(.mpLoadDataUp)
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.schoolViewModel.publishSubData.onNext(.mpLoadDataDown)
        })
        
        view.addSubview(homeSearchView)
        homeSearchView.snp.makeConstraints { (make) in
            make.top.equalTo(LayoutCommon.navHeight)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.height.equalTo(75)
        }
        homeSearchView.mytextField.delegate = self
        
        self.title = "信息共享"
        self.tabBarItem.title = "首页"
        //设置返回位置的坐标系类型
        locService.coordinateType = BMKLocationCoordinateType.BMK09LL
        //设置距离过滤参数
        locService.distanceFilter = kCLDistanceFilterNone
        //设置预期精度参数
        locService.desiredAccuracy = kCLLocationAccuracyBest
        //设置应用位置类型
        locService.activityType = CLActivityType.automotiveNavigation
        //设置是否自动停止位置更新
        locService.pausesLocationUpdatesAutomatically = false
        //设置是否允许后台定位
        locService.allowsBackgroundLocationUpdates = false
        //设置位置获取超时时间
        locService.locationTimeout = 10
        //设置获取地址信息超时时间
        locService.reGeocodeTimeout = 10
        locService.requestLocation(withReGeocode: true, withNetworkState: true) { [weak self] (res, state, error) in
            if let strongSelf = self {
                guard let location2D = res?.location else { return }
                strongSelf.currentLocation = location2D
                let userModel = UserInfo.shareInstance.userModel()
                userModel.latitude = String(location2D.coordinate.latitude)
                userModel.longitude = String(location2D.coordinate.longitude)
                UserInfo.shareInstance.setUserModel(model: userModel)
                strongSelf.tableView.mj_header.beginRefreshing()
            }
        }
    }
}



